package org.phoenix.mall.admin.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;

public class AuthUtil {

    public static String getToken(String userId,String key){
        return JWT.create().withAudience(userId).sign(Algorithm.HMAC256(key));
    }

    public static void verify(String token,String key){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(key)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new RuntimeException("无效的Token");
        }
    }

    public static Integer getUserId(String token){
        String userId = JWT.decode(token).getAudience().get(0);
        return Integer.valueOf(userId);
    }
}
